var canvas;
var ctx;

var bricks;
var ball;

var timer=0;

function init(cv){
	canvas = cv;
	ctx = cv.getContext('2d');
	
	ball = Ball(Math.random()*200,150);
	bricks = Bricks();
	
	var self = {
		start:function(){
			self.stop();
			timer = setInterval(function(){
				clear();
				ball.move();
				bricks.draw();
				ball.draw();
			}, 10);
				  
		},
		stop:function(){
			clearInterval(timer);	 
		},
		prepare:function(){
			bricks.draw();		
		} 
	};
	return self;
}

function Bricks(){
	var height=20, width=canvas.width / 15;
	var self={
		height: height, 
		width:  width,
		matrix:[[1,1,1,1,0,1,1,1,1,0,1,0,1,0,1],
				[1,0,0,0,0,1,0,0,0,0,1,0,1,0,1],
				[1,0,0,1,0,1,1,1,1,0,1,0,1,0,1],
				[1,1,1,1,0,1,0,0,0,0,0,1,0,1,0]],
		draw:function(){
			for (var i=0;i<self.matrix.length;i++) {
				for (var j=0;j<self.matrix[0].length;j++) {
					if (self.matrix[i][j]) {
						drawRect(j*width, i*height, width, height);
					}
				}
			}
		}
	};
	return self;
}


function Ball(ix, iy) {
	var x=ix,y=iy;
	var dx=2,dy=4;
	var r=10;
	var self={
		move:function(){
			//hit the edge ?
			if (x>(canvas.width-r) || x<r/2) {
				dx*=(-1);
			}
			if (y>(canvas.height-r) || y<r/2) {
				dy*=(-1);
			}
			//hit a brick?
			b_width=bricks.width; b_height=bricks.height;
			rows=bricks.matrix.length; cols=bricks.matrix[0].length;
			row = Math.floor(y/b_height);
			col = Math.floor(x/b_width);
			if (y < b_height * rows && row>=0 && col>=0 && bricks.matrix[row][col]){
				bricks.matrix[row][col]=0;
				dy*=(-1);
			}

			x+=dx; y+=dy;
		},
		draw:function(){
			drawCircle(x,y,r);
		},
	};
	return self;
}


function clear(){
	ctx.clearRect(0,0,canvas.width,canvas.height);
}

function drawRect(x,y,w,h){
	ctx.beginPath();
	ctx.rect(x,y,w,h);
	ctx.closePath();
	ctx.fill();
}
function drawCircle(x,y,r){
	ctx.beginPath();
	ctx.arc(x, y, r, 0, Math.PI*2, true);
	ctx.closePath();
	ctx.fill();
}
